package models

import (
	"blog/internal/pkg/password"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type UserStatus int8

const (
	UserActive UserStatus = 1
	UserBanned UserStatus = 0
)

type User struct {
	ID          uint64     `gorm:"primaryKey;comment:主键ID"`
	Username    string     `gorm:"type:varchar(50);not null;uniqueIndex;comment:用户名"`
	Password    string     `gorm:"type:varchar(200);not null;comment:密码"`
	Status      UserStatus `gorm:"default:1;comment:状态 1正常 0禁用"`
	LastLoginAt *time.Time `gorm:"index;comment:最后登录时间"`
	LastLoginIP string     `gorm:"type:varchar(45);comment:最后登录IP"`
	CreatedAt   time.Time  `gorm:"autoCreateTime;index;comment:创建时间"`
	UpdatedAt   time.Time  `gorm:"autoUpdateTime;comment:更新时间"`
}

func (User) TableName() string {
	return "users"
}

// BeforeSave 密码加密钩子
func (u *User) BeforeSave(tx *gorm.DB) error {
	if tx.Statement.Changed("Password") {
		hashed, err := password.GeneratePassword(u.Password)
		if err != nil {
			return fmt.Errorf("密码加密失败: %w", err)
		}
		u.Password = hashed
	}
	return nil
}

// MarshalJSON 安全序列化方法
func (u User) MarshalJSON() ([]byte, error) {
	type Alias User
	return json.Marshal(&struct {
		Password string `json:"-"`
		Alias
	}{
		Password: "",
		Alias:    (Alias)(u),
	})
}
